import express from 'express';
import cors from 'cors';
import { createServer } from 'http';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const NeteaseCloudMusicApi = require('NeteaseCloudMusicApi');

console.log('NeteaseCloudMusicApi 对象:', NeteaseCloudMusicApi);

const app = express();
const PORT = 3000;

// 启用CORS
app.use(cors());

// 代理所有API请求到网易云音乐API
app.use('/', async (req, res) => {
  try {
    const path = req.path.replace(/^\//, '');

    // 如果路径为空，返回API列表
    if (!path) {
      return res.json({
        code: 200,
        message: '网易云音乐API代理服务',
        apis: Object.keys(NeteaseCloudMusicApi).filter(key => typeof NeteaseCloudMusicApi[key] === 'function')
      });
    }

    console.log(`请求的API路径: ${path}`);
    console.log('NeteaseCloudMusicApi 可用API:', Object.keys(NeteaseCloudMusicApi).filter(key => typeof NeteaseCloudMusicApi[key] === 'function'));

    // 检查API是否存在
    if (typeof NeteaseCloudMusicApi[path] !== 'function') {
      return res.status(404).json({
        code: 404,
        message: `API ${path} 不存在`
      });
    }

    // 调用对应的API
    const query = req.query;
    const result = await NeteaseCloudMusicApi[path](query);

    // 返回API结果
    res.json(result);
  } catch (error) {
    console.error('API调用错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 启动服务器
const server = createServer(app);
server.listen(PORT, () => {
  console.log(`网易云音乐API代理服务运行在 http://localhost:${PORT}`);
});